package com.wanpinghui.supplier.user.company;

import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.wanpinghui.supplier.R;
import com.wanpinghui.supplier.common.BaseActivity;
import com.wanpinghui.supplier.widgets.TimeSelectorDialog;
import com.wanpinghui.wphlibrary.WPHSdk;
import com.wanpinghui.wphlibrary.common.dialog.LoadingDialog;
import com.wanpinghui.wphlibrary.model.business.BusinessService;
import com.wanpinghui.wphlibrary.model.user.UserInfoService;
import com.wanpinghui.wphlibrary.model.user.bean.CompanyBean;
import com.wanpinghui.wphlibrary.photovideo.bean.BaseUrlBean;
import com.wanpinghui.wphlibrary.photovideo.bean.UploadFileBean;
import com.wanpinghui.wphlibrary.photovideo.interfaces.OnActionListener;
import com.wanpinghui.wphlibrary.photovideo.view.ClipActivity;
import com.wanpinghui.wphlibrary.photovideo.view.ProductImageUploadView;
import com.wanpinghui.wphlibrary.widgets.ThrottleButton;
import com.yunshl.yunshllibrary.utils.NumberUtil;
import com.yunshl.yunshllibrary.utils.TextUtil;
import com.yunshl.yunshllibrary.utils.TimeUtil;
import com.yunshl.yunshllibrary.view.YunShlEditText;

import org.xutils.view.annotation.ContentView;

import java.util.ArrayList;
import java.util.List;

import me.nereo.multi_image_selector.PhotoPickManager;
import retrofit.callback.YRequestCallback;

/**
 * Created by tg596 on 2018/1/24.
 */
@ContentView(R.layout.layout_activity_business_info)
public class BusinessInformationActivity extends BaseActivity {

    private static final int REQUEST_SELECT_PHOTO = 0x11;
    private static final int CLIP_PHOTO = 0x13;


    private boolean isMore;

    private ArrayList<UploadFileBean> mImageList;//图片
    private TimeSelectorDialog dialog;
    private ImageView mViewBacktrack;
    private TextView tv_warning_text;
    /**
     * 请输入
     */
    private YunShlEditText mEdtCompanyName;

    private YunShlEditText mEdtCompanyType;

    private YunShlEditText mEdtCompanyAddr;

    private YunShlEditText mEdtRegisteredCapital;

    private TextView mTvRegisteredTime;

    private YunShlEditText mEdtRegistrationAuthority;

    private YunShlEditText mEdtBusinessScope;

    private YunShlEditText mEdtRegistrationNumber;

    private YunShlEditText mEdtLegalRepresentative;
    private LinearLayout mLlMore;
    /**
     * 查看更多
     */
    private TextView mTvLookmore;
    private ProductImageUploadView mPiuvRemarkImage;
    /**
     * 下一步
     */
    private ThrottleButton mBtnNext;
    private LinearLayout mLlRootview;

    private CompanyBean bean;

    private long registered_date;

    @Override
    public String getName() {
        return null;
    }

    @Override
    public boolean isBar() {
        return false;
    }

    @Override
    public void initViews() {
        mViewBacktrack = (ImageView) findViewById(R.id.mViewBacktrack);
        mEdtCompanyName = (YunShlEditText) findViewById(R.id.edt_company_name);
        mEdtCompanyType = (YunShlEditText) findViewById(R.id.edt_company_type);
        mEdtCompanyAddr = (YunShlEditText) findViewById(R.id.edt_company_addr);
        mEdtRegisteredCapital = (YunShlEditText) findViewById(R.id.edt_registered_capital);
        mTvRegisteredTime = (TextView) findViewById(R.id.tv_registered_time);
        mEdtRegistrationAuthority = (YunShlEditText) findViewById(R.id.edt_registration_authority);
        mEdtBusinessScope = (YunShlEditText) findViewById(R.id.edt_business_scope);
        mEdtRegistrationNumber = (YunShlEditText) findViewById(R.id.edt_registration_number);
        mEdtLegalRepresentative = (YunShlEditText) findViewById(R.id.edt_legal_representative);
        mLlMore = (LinearLayout) findViewById(R.id.ll_more);
        mTvLookmore = (TextView) findViewById(R.id.tv_lookmore);
        mPiuvRemarkImage = (ProductImageUploadView) findViewById(R.id.piuv_remark_image);
        mBtnNext = (ThrottleButton) findViewById(R.id.btn_next);
        mLlRootview = (LinearLayout) findViewById(R.id.ll_rootview);
        tv_warning_text = (TextView)findViewById(R.id.tv_warning_text);
    }

    @Override
    public void bindEvents() {
        mViewBacktrack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mTvRegisteredTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog == null) {
                    dialog = new TimeSelectorDialog(BusinessInformationActivity.this);
                    dialog.setBindClickListener(new TimeSelectorDialog.BindClickListener() {
                        @Override
                        public void selectTime(long startTime ) {
                            registered_date = startTime;
                            if (startTime > System.currentTimeMillis()){
                                showWarningText("所选日期不能大于当前日期");
                            }else {
                                mTvRegisteredTime.setText(TimeUtil.format(startTime, "yyyy-MM-dd"));
                            }

                        }
                    });
                }
                dialog.setTime(mTvRegisteredTime.getText().toString());
                dialog.show();
            }
        });
        mPiuvRemarkImage.setOnActionListener(new OnActionListener() {
            @Override
            public void onItemDelete(int position) {

                mImageList.remove(position);
                mPiuvRemarkImage.setData(mImageList);
                //  notifyImageDataChange();
            }

            @Override
            public void onItemClick(int position) {

//                Intent intent = new Intent(FeedbackActivity.this, LookPhotoActivity.class);
//
//                intent.putExtra(LookPhotoActivity.PARAMS_DATA,mImageList);
//
//                intent.putExtra(LookPhotoActivity.PARAMS_SHOW_DELETE,true);
//
//                intent.putExtra(LookPhotoActivity.PARAMS_CURRENT_INDEX,position);
//
//                startActivity(intent);

            }

            @Override
            public void onAddMoreClick() {

                PhotoPickManager.selectPicNoCamera(BusinessInformationActivity.this, REQUEST_SELECT_PHOTO, 9, false, mImageList == null ? 0 : mImageList.size());
            }

            @Override
            public void onItemPositionChange() {

            }
        });
        mTvLookmore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isMore) {
                    isMore = false;
                    mLlMore.setVisibility(View.GONE);
                    mTvLookmore.setText("查看更多");
                } else {
                    isMore = true;
                    mLlMore.setVisibility(View.VISIBLE);
                    mTvLookmore.setText("收起");
                }
            }
        });
        mBtnNext.setOnThrottleClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                final CompanyBean companyBean = new CompanyBean();
                companyBean.setCompany_name(mEdtCompanyName.getTextString());
                companyBean.setCompany_type(mEdtCompanyType.getTextString());
                companyBean.setRegistered_capital(NumberUtil.string2double(mEdtRegisteredCapital.getTextString()));
                companyBean.setRegistered_date(registered_date/1000);
                companyBean.setRegistered_address(mEdtCompanyAddr.getTextString());
                companyBean.setRegistration_authority(mEdtRegistrationAuthority.getTextString());
                companyBean.setCompany_scope(mEdtBusinessScope.getTextString());
                companyBean.setRegistered_number(mEdtRegistrationNumber.getTextString());
                companyBean.setLegal_person(mEdtLegalRepresentative.getTextString());
                if (bean != null)
                companyBean.setId(bean.getId());

                if (mImageList != null && mImageList.size()>0){
                    LoadingDialog.Build(BusinessInformationActivity.this).setContent("正在上传").show();
                    WPHSdk.getService(BusinessService.class).uploadPictures(mImageList, new YRequestCallback<List<BaseUrlBean>>() {
                        @Override
                        public void onSuccess(List<BaseUrlBean> var1) {
                            if (var1 != null && var1.size()>0){
                                companyBean.setCertificates(new Gson().toJson(var1));
                                saveCompanyRegister(companyBean);
                            }
                        }

                        @Override
                        public void onFailed(int var1, String message) {
                            LoadingDialog.dismissDialog();
                        }

                        @Override
                        public void onException(Throwable var1) {
                            LoadingDialog.dismissDialog();
                        }
                    });

                }else {
                    saveCompanyRegister(companyBean);



                }

            }

            private void saveCompanyRegister(CompanyBean companyBean) {
                WPHSdk.getService(UserInfoService.class)
                        .saveCompanyRegister(companyBean, new YRequestCallback<CompanyBean>() {
                            @Override
                            public void onSuccess(CompanyBean var1) {
                                Intent intent = new Intent(BusinessInformationActivity.this, CompanyBaseInfoActivity.class);
                                if (bean != null) {
                                    intent.putExtra("bean", bean);
                                }

                                startActivity(intent);
                                LoadingDialog.dismissDialog();
                            }

                            @Override
                            public void onFailed(int var1, String message) {
                                showWarningText(message);
                                LoadingDialog.dismissDialog();
                            }

                            @Override
                            public void onException(Throwable var1) {
                                LoadingDialog.dismissDialog();
                            }
                        });
            }


        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_SELECT_PHOTO:
                if (data != null && resultCode == Activity.RESULT_OK) {
                    Intent intent = new Intent(BusinessInformationActivity.this, ClipActivity.class);
                    intent.putExtra("data", PhotoPickManager.getPhoto(data));
                    intent.putExtra("scale",5);
                    startActivityForResult(intent, CLIP_PHOTO);
                }
                break;
            case CLIP_PHOTO:
                if (resultCode == Activity.RESULT_OK && data != null) {
                    ArrayList<UploadFileBean> list = data.getParcelableArrayListExtra("result");
                    if (list != null) {
                        if (mImageList == null) {
                            mImageList = new ArrayList<>();
                        }
//                        ArrayList list = data.getParcelableArrayListExtra("result");
                        mImageList.addAll(list);
                        mPiuvRemarkImage.setData(mImageList);
                    }
                }
                break;
        }
    }

    @Override
    public void initData() {

        mEdtRegisteredCapital.setInputType(YunShlEditText.TYPE_NUMBER_DECIMAL);

        bean = getIntent().getParcelableExtra("bean");
        if (bean != null){
            if (bean.getAudit_status() == 21 ) {
                tv_warning_text.setVisibility(View.VISIBLE);
                tv_warning_text.setText(bean.getRemark());
            }
            mEdtCompanyName.setText(bean.getCompany_name());
            mEdtCompanyType.setText(bean.getCompany_type());
            if (bean.getRegistered_capital()>0){
                mEdtRegisteredCapital.setText(NumberUtil.double2String(bean.getRegistered_capital()));
            }
            if (bean.getRegistered_date()>1) {
                registered_date = bean.getRegistered_date() * 1000;
                mTvRegisteredTime.setText(TimeUtil.format(registered_date, "yyyy-MM-dd"));
            }
            mEdtCompanyAddr.setText(bean.getRegistered_address());
            mEdtRegistrationAuthority.setText(bean.getRegistration_authority());
            mEdtBusinessScope.setText(bean.getCompany_scope());
            mEdtRegistrationNumber.setText(bean.getRegistered_number());
            mEdtLegalRepresentative.setText(bean.getLegal_person());
            if(TextUtil.isNotEmpty(bean.getCertificates())) {
                List<BaseUrlBean> baseUrlBeanList = new Gson().fromJson(bean.getCertificates().length() < 3 ? null : bean.getCertificates(), new TypeToken<List<BaseUrlBean>>() {}.getType());
                if (baseUrlBeanList != null && baseUrlBeanList.size() > 0) {
                    for (BaseUrlBean bean : baseUrlBeanList) {
                        if (mImageList == null) {
                            mImageList = new ArrayList<>();
                        }
                        List<String> list = new ArrayList<>();
                        list.add(bean.getUrl());
                        mImageList.addAll(UploadFileBean.create(list));
                        mPiuvRemarkImage.setData(mImageList);

                    }
                }
            }
        }
        String name = getIntent().getStringExtra("name");
        if (TextUtil.isNotEmpty(name)){
            mEdtCompanyName.setText(name);
        }

    }

}
